package com.jihui.jihuipicturebackend.aop;

import com.jihui.jihuipicturebackend.annotation.CheckAuth;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.model.entity.User;
import com.jihui.jihuipicturebackend.model.enums.UserRoleEnum;
import com.jihui.jihuipicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    //@Around("execution(* com.jihui.jihuipicturebackend.controller.*.*(..))")
    @Around("@annotation(checkAuth)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, CheckAuth checkAuth) throws Throwable {
        String mustRole = checkAuth.mustRole();
        // 获取全局HttpServletRequest对象
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 获取用户登录信息并判断当前用户是否登录
        User userLoginVo = userService.getUserLoginVOByRequest(request);

        // 获取当前用户的角色
        UserRoleEnum userRoleEnum = UserRoleEnum.getUsrRoleEnum(mustRole);
        // 不需要权限，直接放行
        if(userRoleEnum == null){
            return joinPoint.proceed(); // 执行原方法
        }

        // 必须有权限才能通过
        UserRoleEnum userRole = UserRoleEnum.getUsrRoleEnum(userLoginVo.getUserRole());
        // 没有权限
        if(userRole == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "当前用户没有权限访问该接口");
        }
        // 有权限,且必须是管理员才能访问
        if(UserRoleEnum.ADMIN.equals(userRole) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "当前用户没有权限访问该接口");
        }
        // 有权限
        return joinPoint.proceed(); // 执行原方法
    }
}
